<?php

namespace App\Services\WanSdk;

use App\Commons\CommonConstant;
use App\Models\Channels;
use App\Models\Orders;
use App\Services\ServiceBase;
use App\Services\WechatApi\WechatApiOauth;
use App\Services\WxConfigService;

class WanSdkPayService extends ServiceBase
{
    public function getOrderByJssdkAccessToken($appid, $code)
    {
        $wxconfig = WxConfigService::getInstance()->one($appid);
        $channel = Channels::CHANNEL_H5;

        $res = WechatApiOauth::getInstance()->oauthUser($appid, $wxconfig->secret, $code);
        if (!$res) {
            return 6026;
        }
        $channel_openid = $res['openid'];

        // 获取此openid最近一次创单
        $order = Orders::whereRaw("channel_openid='{$channel_openid}' AND channel={$channel}")->orderBy('id', 'desc')->first();

        if (!$order) {
            return 6020;
        }

        // 如果此订单已经被处理过，则跳过
        if (!in_array($order->status, [Orders::PAY_STATUS_CREATE, Orders::PAY_STATUS_RUNING])) {
            return 6021;
        }

        return $order;
    }
}
